#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
class Solution {
    int m, n;
public:
    int cutOffTree(vector<vector<int>>& forest) {
        m = forest.size();
        n = forest[0].size();
        vector<pair<int, int>> trees;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (forest[i][j] > 1)
                {
                    trees.push_back({ i,j });
                }
            }
        }
        sort(trees.begin(), trees.end(), [&](const pair<int, int>& as1, const pair<int, int>& as2) {
            return forest[as1.first][as1.second] < forest[as2.first][as2.second];
            });
        int bx = 0;
        int by = 0;
        int ret = 0;
        for (auto& [a, b] : trees)
        {
            int step = bfs(forest, bx, by, a, b);
            if (step == -1)
            {
                return -1;
            }
            ret += step;
            bx = a;
            by = b;
        }
        return ret;
    }
    bool aq[51][51];
    int dx[4] = { 1,-1,0,0 };
    int dy[4] = { 0,0,1,-1 };
    int bfs(vector<vector<int>>& f, int a, int b, int bx, int by)
    {
        if (a == bx && b == by)
        {
            return 0;
        }
        queue<pair<int, int>> aw;
        memset(aq, 0, sizeof(aq));
        aw.push({ a,b });
        aq[a][b] = true;
        int d = 0;
        while (aw.size())
        {
            d++;
            int sz = aw.size();
            while (sz--)
            {
                auto [x, y] = aw.front();
                aw.pop();
                for (int i = 0; i < 4; i++)
                {
                    int er = x + dx[i];
                    int et = y + dy[i];
                    if (er >= 0 && er < m && et >= 0 && et < n && f[er][et] && !aq[er][et])
                    {
                        if (er == bx && et == by)
                        {
                            return d;
                        }
                        aw.push({ er,et });
                        aq[er][et] = true;
                    }
                }
            }
        }
        return-1;
    }
};